let core = require('./core.js');
// 时间格式转换 yyyy/mm/dd
function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate() 
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()  
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
// 时间格式转换 yyyy－mm－dd
function formatTime2(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate() 
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()  
  return [year, month, day].map(formatNumber).join('-')
}

function formatDate(date, split) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  return [year, month, day].map(formatNumber).join(split || '')
}

// 两位数自动补零
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// 计算变化多少天后的日期
function DateAddDay(d, days) {
  var d = new Date(d); 
  return new Date(d.setDate(d.getDate() + days));
}

// 获得本周周日的日期
function FirstDayInThisWeek(d) { 
  var d = new Date(d);  
  return DateAddDay(d, 0 - d.getDay());
}

// 判断类型
function Type(obj) {
  var typeStr = Object.prototype.toString.call(obj).split(" ")[1];
  return typeStr.substr(0, typeStr.length - 1).toLowerCase();
}


//跳转页面，校验登录状态
function href(url, isVerify, inWhiteList = true) {
	// if (isVerify && !store.state.isLogin) {
	// 	store.commit('setReturnUrl', url)
	// 	// #ifdef APP-PLUS
	// 	uni.navigateTo({
	// 		url: '/pages/my/login/login'
	// 	})
	// 	// #endif
	// 	// #ifdef MP
	// 	uni.navigateTo({
	// 		url: '/pages/my/authorize/authorize'
	// 	})
	// 	// #endif
	// } else {
		if (inWhiteList) { //如果在程序的网址白名单中，会走内置webview打开，否则会复制网址提示在外部浏览器打开
			if (url.indexOf('http') == 0) {
				uni.navigateTo({
					url: '/pages/mall/web-view/web-view?url=' + url
				});
			} else if (url.indexOf('pages/tabbar') != -1) {
				uni.switchTab({
					url: url
				});
			} else {
				uni.navigateTo({
					url: url
				});
			}
		} else {
			uni.setClipboardData({
				data: url
			});
			uni.showModal({
				content: '本网址无法直接在程序内打开。已自动复制网址，请在手机浏览器里粘贴该网址',
				showCancel: false
			});
		}
	// }
}

/**
 * 加载更多按钮功能
 * page.data定义moreButton(可由moreButtonDataField更改) moreButton.text作为按钮文本, moreButton.page作为页码
 * @param pageInstance
 * @param url 接口地址
 * @param queryData querystring parameters
 * @param moreButtonDataField morebutton data在page.data中的字段名
 * @param listFieldName 渲染的列表数据再page.data中的字段名
 * @param retDataFieldName 接口返回的列表数据再http response ret.data中的字段名
 * @param dataFormatter function, 处理服务器返回的列表数据，返回处理过后的数组, this指向pageInstance
 */
const fetch = function(pageInstance, url,queryData, moreButtonDataField, listFieldName, retDataFieldName, dataFormatter) {
  let moreButtonData = pageInstance[moreButtonDataField] || {page:1};
  if(moreButtonData.loading || moreButtonData.nomore) {
    return;
 }
  queryData.page = moreButtonData.page;
  pageInstance[moreButtonDataField]['loading'] = true;
  pageInstance[moreButtonDataField]['text'] = '正在加载...';
  pageInstance.$forceUpdate();
  core.get({
    url: url, data: queryData,
	loading:false,
    success(ret, response) {
      let listData = retDataFieldName?ret.data[retDataFieldName]:ret.data;
      let listLength = listData.length;
      if(typeof dataFormatter === 'function') {
        //listData = dataFormatter.apply(pageInstance, [listData, ret.data]) || listData;
		dataFormatter(ret.data);
      }else if(dataFormatter==='unique') {
        function uniqueFormatter(listData) {
          let formattedList = [];
          out:  for(let i in listData) {
            let item = listData[i];
            for(let j in pageInstance[listFieldName]) {
              let originItem = pageInstance[listFieldName][j];
              if(originItem.id==item.id) {
                continue out;
              }
            }
            formattedList.push(item);
          }
          return formattedList;
        }
        listData = uniqueFormatter(listData);
      }
      if(Array.isArray(listData) && listLength>0) {
        pageInstance[listFieldName] = (pageInstance[listFieldName] || []).concat(listData);
        let pagesize = queryData.pagesize || 10;
        
        if(listLength<pagesize) {
		  pageInstance[moreButtonDataField]['page'] = moreButtonData.page + 1;
		  pageInstance[moreButtonDataField]['loading'] = false;
		  pageInstance[moreButtonDataField]['nomore'] = true;
		  pageInstance[moreButtonDataField]['text'] = '—— 我是有底线的 ——';
          //console.log(pageInstance,1)
        }else {
			
			pageInstance[moreButtonDataField]['page'] = moreButtonData.page + 1;
			pageInstance[moreButtonDataField]['loading'] = false;
			pageInstance[moreButtonDataField]['text'] = '加载更多';
			//console.log(pageInstance,2)
        }
      }else {
        let text = moreButtonData.page == 1 ? '暂无数据' : '—— 我是有底线的 ——';
        let nothing = moreButtonData.page == 1 ? true : false;
        console.log(nothing)
		pageInstance[moreButtonDataField]['nomore'] = true;
		pageInstance[moreButtonDataField]['text'] = text;
		pageInstance[moreButtonDataField]['nothing'] = nothing;
		//console.log(pageInstance,3)
      }
	  pageInstance.$forceUpdate();
    },
    fail(ret, response) {
		pageInstance[moreButtonDataField]['loading'] = false;
		pageInstance[moreButtonDataField]['text'] = '加载更多';
    }
  })
};
const getRemoteDataCached = async function(options) {
  let data, url = options.url, cacheKey = options.cacheKey, useCache = options.useCache===undefined ? true : options.useCache,
    retDataKey = options.dataKey;
  if(useCache) {
    data = core.getCache(cacheKey);
  }
  if(!data) {
    data = await (new Promise(function(resolve, reject) {
      core.get({
        url: url,
        data: options.data || '',
        loading:false,
        success(ret) {
          resolve(retDataKey ? ret.data[retDataKey]:ret.data);
        },
        fail(ret) {
          reject(ret);
        }
      });
    }));
    core.setCache(cacheKey, data, 1800);
  }
  return data;
};

/**
 * 获取城市数据，包含省份
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 */
const getAreaTree = function (useCache=true) {
  let cacheKey = 'area_tree';
  return getRemoteDataCached({
    url: '/fitness.common/area_tree',
    data: {},
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};

/**
 * 获取城市数据，包含省份
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 */
const getAllCities = function (useCache=true) {
  let cacheKey = 'cities';
  return getRemoteDataCached({
    url: '/fitness.common/cities',
    data: {},
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};


module.exports = {
  formatTime: formatTime,
  formatDate: formatDate,
  formatTime2,
  DateAddDay: DateAddDay,
  FirstDayInThisWeek: FirstDayInThisWeek,
  type: Type,
  addZero: formatNumber,
  href: href,
  fetch:fetch,
  getAreaTree:getAreaTree,
  getAllCities:getAllCities
}